import { Color, Matrix4, Vector3, Quaternion } from 'https://unpkg.com/three/build/three.module.js';
import { initShaders } from '../jsm/Utils.js';
import lib from '../jsm/ThreeLib.js';
import Poly from '../jsm/Poly.js'
import Sky from '../jsm/Sky.js'
import ShapeGeo from '../jsm/ShapeGeo.js';

window.onload = function () {

    const backColor = new Color("rgba(0,0,0,1)");

    const canvas = document.getElementById("canvas");
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    const gl = canvas.getContext("webgl");
    //开启颜色合成,才会有透明度的感觉
    gl.enable(gl.BLEND);
    gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);

    //初始化着色器
    initShaders(gl,
        document.querySelector("#vertexShader").innerText,
        document.querySelector("#fragmentShader").innerText);
    lib.clearCanvas(gl, new Color("rgba(0,0,0,1)"), 1);




    const verticeLib = [
        1.0, 1.0, 1.0,
        -1.0, 1.0, 1.0,
        -1.0, -1.0, 1.0,
        1.0, -1.0, 1.0,
        1.0, -1.0, -1.0,
        1.0, 1.0, -1.0,
        -1.0, 1.0, -1.0,
        -1.0, -1.0, -1.0,
    ];

    const indices = [
        0, 1,
        1, 2,
        2, 3,
        3, 0,

        0, 5,
        1, 6,
        2, 7,
        3, 4,

        4, 5,
        5, 6,
        6, 7,
        7, 4
    ];

    const arr = [];
    indices.forEach(n => {
        const i = n * 3
        arr.push(
            verticeLib[i] / 5,
            verticeLib[i + 1] / 5,
            verticeLib[i + 2] / 5,
        )
    })

    let poly = new Poly({
        gl: gl,
        vertices: arr,
        size: 3
    })


    var viewMatrix = new Matrix4().lookAt(
        new Vector3(0, 0.2, 1),
        new Vector3(0, 0, 0),
        new Vector3(0, 1, 0),
    );
    var modelMatrix = new Matrix4();

    let angle = 0;

    let u_Vm4 = gl.getUniformLocation(gl.program, 'u_ViewMatrix');
    gl.uniformMatrix4fv(u_Vm4, false, viewMatrix.elements);

    let u_Mm4 = gl.getUniformLocation(gl.program, 'u_ModelMatrix');
    gl.uniformMatrix4fv(u_Mm4, false, modelMatrix.elements);

    const miny = -0.7;//极小值
    const maxy = 0.7;//极大值
    let cury = maxy;//当前值
    let vy = 0;//速度
    const ay = -0.001;//加速度
    const bounce = 1;

    (function ani() {
        angle += 0.01;

        // vy += ay;
        // cury += vy;
        // modelMatrix.makeRotationY(angle);
        // modelMatrix.setPosition(0, cury, 0);
        // if (modelMatrix.elements[13] < miny) {
        //     cury = miny;
        //     vy *= -bounce;
        // }

        gl.uniformMatrix4fv(u_Mm4, false, modelMatrix.elements);
        poly.draw(["LINES"]);

        requestAnimationFrame(ani);
    })()


}